package com.example.mcdonaldapplication.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.example.mcdonaldapplication.databinding.ActivityIndentBinding
import com.example.mcdonaldapplication.info.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class IndentActivity : AppCompatActivity() {
    private lateinit var binding: ActivityIndentBinding
    private val goodsList = ArrayList<GoodsInfo>()
    private val cartList = ArrayList<CartInfo>()
    private val serverIP = ServerIP.getIp()
    private var i = 0

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityIndentBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
        val from = intent.getStringExtra("from")
        if(from != "takeaway"){
            binding.ccTakeawayAddress.visibility = View.GONE
        }else{
            binding.ccTakeawayAddress.visibility = View.VISIBLE
        }
        val prefs = getSharedPreferences("user", Context.MODE_PRIVATE)
        val username = prefs.getString("username", "")
        val mobile = prefs.getString("mobile", "")
        val balance = prefs.getString("balance", "0")!!
        val address = intent.getStringExtra("address")
        binding.tvUsername.text = username
        binding.tvPhone.text = mobile
        binding.tvAddress.text = address
        binding.tvWalletMoney.text = balance
        //获取合计价格
        val price = intent.getIntExtra("price",0)
        binding.tvTotalPrice3.text ="合计¥:${price}"   //合计
        getAllGoods()
        getUser()
        //点击提交订单
        binding.tvSubmit.setOnClickListener {
            if(price > balance.toDouble()){
                Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show()
            }else{
                buyGood()
            }
        }
    }

    private fun buyGood(){
        thread{

            val goods = ArrayList<GoodInfo>()
            for(good in cartList){
                val cartGood = GoodInfo(good.gid,"${good.num}", "1")
                goods.add(cartGood)
            }
            val goodsJson = Gson().toJson(goods)
            val prefs = getSharedPreferences("user", Context.MODE_PRIVATE)
            val uid = prefs.getInt("uid", 0)
            val formBody: FormBody = FormBody.Builder()
                .add("good", goodsJson)
                .add("uid", uid.toString())
                .add("tid", "")
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/goods/buyGoods")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJSONWithGSON(responseData)
        }
    }

    private fun parseJSONWithGSON(jsonData: String) {
        val jsonObject = JSONObject(jsonData)
        val message = jsonObject.getString("message")
        val address = intent.getStringExtra("address")
        val price = intent.getIntExtra("price",0)
        if (message == "购买成功") {
            val intent = Intent(this,IndentDetailActivity::class.java)
            intent.putExtra("price",price)
            if(address != null){
                intent.putExtra("address",address)
            }
            finish()
            startActivity(intent)
        }
    }

    private fun getAllGoods(){
        thread {
            val formBody: FormBody = FormBody.Builder()
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/goods/queryAll")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJSONGetAllGoods(responseData)
        }
    }

    private fun parseJSONGetAllGoods(jsonData: String) {
        val jsonObject = JSONObject(jsonData)
        val message = jsonObject.getString("message")
        val data = jsonObject.getString("data")
        if (message == "查询成功") {
            val gson = Gson()
            val typeOf = object : TypeToken<List<GoodsInfo>>() {}.type
            val goodsInfoList = gson.fromJson<List<GoodsInfo>>(data, typeOf)
            for (good in goodsInfoList) {
                goodsList.add(good)
            }
            val prefs = getSharedPreferences("cart", Context.MODE_PRIVATE)
            i = 0
            for (goods in goodsList) {
                val num = prefs.getInt("${goods.name}num", 0)
                val price = prefs.getString("${goods.name}price", "0")!!
                val img = prefs.getString("${goods.name}img", "0")!!
                val gid = prefs.getString("${goods.name}gid", "0")!!
                if (num >= 1) {
                    cartList.add(i, CartInfo(gid, goods.name, num, price, img))
                    i++
                }
            }
        }
    }
    private fun getUser(){
        val prefs = getSharedPreferences("user", Context.MODE_PRIVATE)
        val balance = prefs.getString("balance", "0.0")
        binding.tvWalletMoney.text = "$balance"
    }
}